<?php
require_once('../../carbox.php');
if(!carbox_check_session( ) || $_SESSION['profile'] < 3)
	header('Location: http://'.$_SERVER['HTTP_HOST'].'/carbox/login.php');
$params = $_POST["params"];
$process_id = $params[0];
array_splice($params, 0, 1);
$prev_tid = NULL;
$document_id = NULL;
$rt = "ok";
$pdo = carbox_get_database_settings("/home/www-data/database_carbox.conf");
$pdo->beginTransaction( );
for($j = 0; $j < count($params); ++$j) {
	if($params[$j]["exclude"] == "true") {
		$query = carbox_query("DELETE FROM Page WHERE id = :pid", array(":pid" => $params[$j]["page_id"]), $pdo);
		if($query["fail"]) {
			$rt = "error del page";
			break;
		}
	}
	if(!empty($params[$j]["group_id"])) {
		$query = carbox_query(
			"INSERT INTO Document (type_id, process_id, created_on) VALUES(:tid, :pid, NOW( ))",
			array(":tid" => $params[$j]["type_id"], ":pid" => $process_id),
			$pdo
		);
		if($query["fail"]) {
			$rt = "error insert doc";
			break;
		}
		$document_id = carbox_query("SELECT id FROM Document ORDER BY id DESC LIMIT 1", NULL, $pdo);
		$document_id = $document_id["result"][0]["id"];
		$group = $params[$j]["group_id"];
		for($i = $j; $i < count($params); ++$i) {
			if($params[$i]["group_id"] == $group) {
				$query = carbox_query(
					"UPDATE Page SET document_id = :did, number_relative = :pr, number_absolute = :pa, blank = :b WHERE id = :page_id",
					array(
						":did" => $document_id,
						":pr" => $params[$i]["page_relative"],
						":pa" => $params[$i]["page_absolute"],
						":page_id" => $params[$i]["page_id"],
						":b" => ($params[$i]["is_blank"] == 'true')? 1 : NULL
					),
					$pdo
				);
				if($query["fail"]) {
					$rt = "error update page";
					break;
				}
				//array_splice($params, $i--, 1, NULL);
				$params[$i]["group_id"] = NULL;
			}
		}
	}
	carbox_query(
        	"INSERT INTO DocumentAction (document_id, user_id, action_id, date) VALUES (:did, :uid, 3, NOW( ))",
	      array(':uid' => $_SESSION['uid'], ':did' => $document_id),
			$pdo
	);
}
if($rt == "ok") {
	for($i = 0; $i < count($params); ++$i) {
		$query = carbox_query("DELETE FROM Document WHERE id = :did", array(":did" => $params[$i]["document_id"]), $pdo);
		if($query["fail"]) {
			$pdo->rollback( );
			$rt = "error del doc";
			break;
		}
	}
}
$pdo->commit( );
echo json_encode($rt);
?>
